// import axios from 'axios';
import { dateStrFormat } from './formatTime';
import request from '@/utils/request';
import { Session } from '@/utils/storage';
import * as XLSX from 'xlsx';

// const BASE_URL_FILE = 'http://8.141.89.4:7788/img';
// const BASE_URL_FILE = '/uploads'; // 文件上传地址
const BASE_URL_FILE = `${import.meta.env.VITE_API_URL}/uploads`;

export const addWindowResizeHandler = function (handler: any) {
	let oldHandler: any = window.onresize;
	if (typeof window.onresize != 'function') {
		window.onresize = handler;
	} else {
		window.onresize = function () {
			oldHandler();
			handler();
		};
	}
};
export const getNodeUUid = function () {
	return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
		var r = (Math.random() * 16) | 0,
			v = c == 'x' ? r : (r & 0x3) | 0x8;
		return v.toString(16);
	});
};

export const isJSON = (str: string) => {
	let result = false;
	try {
		JSON.parse(str);
		result = true;
	} catch (e) {
		result = false;
	}
	return result;
};

// 上传文件
export function uploadFile(file: any, imgName: any, data = { isPublic: 1, isCatalogue: 0, parentId: 0 }) {
	return new Promise((resolve, reject) => {
		// 创建一个FormData对象
		var formData = new FormData();
		// 将文件添加到formData中
		formData.append('file', file);
		// 发起PUT请求
		request
			.put(`${BASE_URL_FILE}?isPublic=${data.isPublic}&isCatalogue=${data.isCatalogue}&parentId=${data.parentId}`, formData, {
				headers: {
					'Content-Type': 'multipart/form-data',
				},
				onUploadProgress: function (progressEvent: any) {
					var percentComplete = (progressEvent.loaded / progressEvent.total) * 100;
					console.log('上传进度：' + percentComplete + '%');
				},
			})
			.then(function (response) {
				console.log('文件上传成功！', response);
				const idRegex = /id: ([\w-]+)/;
				const match = response.match(idRegex);
				const id = match && match[1];
				resolve(id);
			})
			.catch(function (error) {
				console.log('文件上传失败！');
				reject(error);
			});
	});
}

// 2024-01-31T00:00:00+08:00  格式转日期 不含具体时间点
export const formatWithDate = (date: any) => {
	return dateStrFormat(date).substring(0, 10);
};

/***** 下划线命名转驼峰 ****/
export const underlineToCamelCase = (underlineName: string) => {
	var words = underlineName.split('_');
	var camelCaseName = words[0];
	for (var i = 1; i < words.length; i++) {
		var capitalizedWord = words[i].charAt(0).toUpperCase() + words[i].slice(1);
		camelCaseName += capitalizedWord;
	}
	return camelCaseName;
};

/*** 获取文件链接 */
export const getFileUrl = (fileId: string) => {
	return new Promise((resolve, reject) => {
		request({
			url: `${BASE_URL_FILE}?fileId=${fileId}`,
			method: 'get',
		}).then((res) => {
			if (res.fileType && res.fileType.includes('image')) {
				resolve(res.filePath + '?token=' + Session.get('token'));
			}
		});
	});
};

/*** 删除上传的文件 */
export const delFile = (fileId: string) => {
	return new Promise((resolve, reject) => {
		request({
			url: `${BASE_URL_FILE}?fileId=${fileId}`,
			method: 'DELETE',
		}).then((res) => {
			resolve(res);
		});
	});
};
/** 导出文件 -- XLSX*/
export const exportDataToExcel = (data: any, filename: any) => {
	// 创建一个新的工作簿
	const workbook = XLSX.utils.book_new();

	// 将数据转换为工作表
	const worksheet = XLSX.utils.json_to_sheet(data);

	// 将工作表添加到工作簿
	XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

	// 生成Excel文件
	XLSX.writeFile(workbook, filename);
};
